import type { Context } from 'hono';
import { AuthService, type JWTPayload } from '../services/authService';

export interface TRPCContext {
  requestId: string;
  timestamp: string;
  user?: JWTPayload;
  ipAddress?: string;
  userAgent?: string;
}

export async function createTRPCContext(c: Context): Promise<TRPCContext> {
  const authHeader = c.req.header('Authorization');
  const ipAddress = c.req.header('x-forwarded-for') || c.req.header('x-real-ip') || 'unknown';
  const userAgent = c.req.header('user-agent') || 'unknown';

  let user: JWTPayload | undefined;

  if (authHeader && authHeader.startsWith('Bearer ')) {
    const token = authHeader.substring(7);
    try {
      user = AuthService.verifyToken(token);
    } catch (error) {
      // Token无效，user保持undefined
    }
  }

  return {
    requestId: crypto.randomUUID(),
    timestamp: new Date().toISOString(),
    user,
    ipAddress,
    userAgent,
  };
}
